package com.nulldev.util.java.utils;

import java.awt.Color;
import java.awt.Robot;
import java.awt.event.KeyEvent;

import com.nulldev.util.java.utils.color.ColorUtil;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;

public class RobotUtils {

	private static Robot r;
	private static final Logger log = LoggerFactory.getLogger();
	private static void init() {
		try {
			if (r == null) {
				r = new Robot();
			}
		}catch (Exception e) {
			log.error("Failed to create instance.", e);
		}
	}
	
	public static Color pixelAt(final int x, final int y) {
		init();
		if (r != null) {
			return r.getPixelColor(x, y);
		}else {
			log.error("Failed to run 'pixelAt()': Robot is null.");
			return ColorUtil.TRANSPARENT;
		}
	}
	
	public static void enter() {
		init();
		if (r != null) {
			r.keyPress(KeyEvent.VK_ENTER);
			r.waitForIdle();
			r.keyRelease(KeyEvent.VK_ENTER);
		}else {
			log.error("Failed to run 'write()': Robot is null.");
		}
	}

	public static void write(final String text) {
		init();
		if (r != null) {
			for (final char x : text.toCharArray()) {
				r.keyPress(KeyEvent.getExtendedKeyCodeForChar(x));
				r.waitForIdle();
				r.keyRelease(KeyEvent.getExtendedKeyCodeForChar(x));
			}
		}else {
			log.error("Failed to run 'write()': Robot is null.");
		}
	}
}
